package com.CMS.client;

import org.gwtmultipage.client.UrlPatternEntryPoint;

import com.CMS.client.ui.data.GestionUserPaneSectionData;
import com.CMS.client.ui.data.LanguageManagerPaneSectionData;
import com.CMS.client.ui.data.MultimediaPaneSectionData;
import com.CMS.client.ui.data.NavigationPaneRecord;
import com.CMS.client.ui.data.PageManagerPaneSectionData;
import com.CMS.client.ui.data.SettingsNavigationPaneSectionData;
import com.CMS.client.ui.view.ContextAreaFactory;
import com.CMS.client.ui.view.LoginView;
import com.CMS.client.ui.widgets.Masthead;
import com.CMS.client.ui.widgets.NavigationPane;
import com.CMS.client.ui.widgets.NavigationPaneHeader;
import com.CMS.server.domain.User;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.grid.events.RecordClickEvent;
import com.smartgwt.client.widgets.grid.events.RecordClickHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.menu.events.ClickHandler;
import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;

@UrlPatternEntryPoint(value = "CMS.html(\\\\?locale=(es|en))?((&|\\\\?)gwt.codesvr=127.0.0.1:9997)?")
public class CMS implements EntryPoint{
	    
	   private static final int NORTH_HEIGHT = 85;
	   private static final String DEFAULT_USER_NAME = "alias";
	   private static final String DEFAULT_PASSWORD = "pass";
	   
	   private CMSConstants constants = GWT.create(CMSConstants.class);
	   
	   private CMSMessage msjError = GWT.create(CMSMessage.class);
	  
	   private VLayout mainLayout;  
	   private HLayout northLayout; 
	   private HLayout southLayout;
	   private VLayout eastLayout; 
	   private VLayout westLayout;
	   private NavigationPaneHeader navigationPaneHeader;

	   	  
	   public void onModuleLoad()
	   {		  
		
		 
		   
		 if((Cookies.getCookie(NameTokens.DEFAULT_PAGE) == null) && (Cookies.getCookie(NameTokens.USSER_SESSION) == null) )
		  {
			  //Cookies.setCookie(NameTokens.DEFAULT_PAGE,UrlManagement.URL);
			  final HTMLPanel panel;
			  final RootPanel rootPanel = RootPanel.get();
			  final TextBox userNameField;
			  final PasswordTextBox passwordField;
			  final Button signInButton;
			    
	          userNameField = new TextBox();
			  passwordField = new PasswordTextBox();
			  signInButton = new Button(constants.labelButtonLogin());
              userNameField.setText(DEFAULT_USER_NAME);
              passwordField.setText(DEFAULT_PASSWORD);
			  
              LoginView view =new LoginView();
			   
              panel = new HTMLPanel(view.getLoginView());
			  panel.add(userNameField, "userNameFieldContainer");
			  panel.add(passwordField, "passwordFieldContainer");
			  panel.add(signInButton,  "signInButtonContainer");
			  			  
			  rootPanel.get("loading").setVisible(false);
			  rootPanel.add(panel);
			  
			  signInButton.addClickHandler(new com.google.gwt.event.dom.client.ClickHandler() {
					
			        @Override
					public void onClick(ClickEvent event)
					{
			          setLoading(signInButton,false,"Accediendo","gwt-Button-disable");
			          if (userNameField.getText().length() == 0 || passwordField.getText().length() == 0)
			          {	  
			        	 SC.say(msjError.messageErrorEmptyUser());
			        	 setLoading(signInButton,true,"Acceder","gwt-Button");         
			          }
					  else
						{
						  UserServiceAsync rpcUser = GWT.create(UserService.class);
						  try 
							{
						        rpcUser.getUserHabilitado(userNameField.getText(), passwordField.getText(), new AsyncCallback<User>() 
						        {

								  @Override
							      public void onFailure(Throwable caught)
								  {
									SC.say(caught.getMessage());
									setLoading(signInButton,true,"Acceder","gwt-Button");
								  }

								  @Override
								  public void onSuccess(User result)
								  {
								  if(result != null)
								  {									
									NameTokens.SET_LANGUAGE = result.getLang().getValue();							  
						            Cookies.setCookie(NameTokens.DEFAULT_PAGE,UrlManagement.URL);
									rootPanel.remove(panel);
									rootPanel.get("loading").setVisible(true);
									Cookies.setCookie(NameTokens.USSER_SESSION,userNameField.getText());
									History.newItem(NameTokens.PRIVILEGE);
									Cookies.setCookie(NameTokens.TOKEN,NameTokens.PRIVILEGE);									
									Window.Location.replace(UrlManagement.URL);
								 }
								 else
								  {	
									SC.say(msjError.messageErrorLoginUser());
									setLoading(signInButton,true,"Acceder","gwt-Button");
								  }		
							    }
									
								});
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}		
					}
				}); 
		  } 
		 else if(Cookies.getCookie(NameTokens.USSER_SESSION) == null && Cookies.getCookie(NameTokens.DEFAULT_PAGE) != null){
	         Cookies.removeCookie(NameTokens.DEFAULT_PAGE);
	         Window.Location.replace(UrlManagement.URL);
		 }
		  else
		  {
			  ManagePages();
		  }
	   }
	 
		  
       private void ManagePages()
       {   
    	  // get rid of scroll bars, and clear out the window's built-in margin,
		  // because we want to take advantage of the entire client area
		  Window.enableScrolling(false);
		  Window.setMargin("0px");			 
		  
		  // initialise the main layout container
		  mainLayout = new VLayout();
		  mainLayout.setWidth100(); 
		  mainLayout.setHeight100(); 
		  
		  // initialise the North layout container
		  northLayout = new HLayout(); 
		  northLayout.setHeight(NORTH_HEIGHT);
		  
		  VLayout vLayout = new VLayout();
		  // add the Masthead to the nested layout container
		  vLayout.addMember(new Masthead());
		  
		  // initialise the Navigation Pane Header 
		  navigationPaneHeader = new NavigationPaneHeader();
		    
		  // add the Application Menu and the Navigation Pane Header to the nested layout container
		  vLayout.addMember(navigationPaneHeader);  
		    
		  
		  // add the nested layout container to the North layout container
		  northLayout.addMember(vLayout);
		  
		  //Inicializo panel de navegacion
		  NavigationPane navigationPane = new NavigationPane();
	
		  
		  //Inicializo la gestion de usuarios  
		  navigationPane.add("Gestion de usuarios", GestionUserPaneSectionData.getRecords(),
					new NavigationPaneClickHandler());
		  
		  //Inicializo la gestion de paginas
		  navigationPane.add("Gestion de paginas", PageManagerPaneSectionData.getRecords(),
					new NavigationPaneClickHandler());
		  
		  //Inicializo la gestion de Idiomas
		  navigationPane.add(constants.LanguageSectionName(), LanguageManagerPaneSectionData.getRecords(),
					new NavigationPaneClickHandler());
		  
		  
		  //Inicializo la gestion de configuracion del sistema
		  navigationPane.add(constants.SettingsSectionName(), SettingsNavigationPaneSectionData.getRecords(),
				  					new NavigationPaneClickHandler());
		  
		  navigationPane.add("Multimedia", MultimediaPaneSectionData.getRecords(), new NavigationPaneClickHandler());
          
      
		  
		  // initialise the West layout container
		  westLayout = navigationPane;
		  
		  
		  // initialise the South layout container
		  southLayout = new HLayout();
		  if(Cookies.getCookie(NameTokens.TOKEN) == null)
		  {	  
			 History.newItem(NameTokens.PRIVILEGE);
			 Cookies.setCookie(NameTokens.TOKEN,NameTokens.PRIVILEGE);
		  }
		  else
			  History.getToken();
		  
		  InstancePage page = new InstancePage(Cookies.getCookie(NameTokens.TOKEN));
		  eastLayout = (VLayout) page.getInstancePage();
		  
		  changeAccionPage(Cookies.getCookie(NameTokens.TOKEN),navigationPane);
		  
		  // set the Navigation Pane and Context Area as members of the South
		  // layout container
		  southLayout.setMembers(westLayout, eastLayout); 
		  
		  // add the North and South layout containers to the main layout container
		  mainLayout.addMember(northLayout); 
		  mainLayout.addMember(southLayout);
		  
		  // add the main layout container to GWT's root panel
		  RootPanel.get("loading").setVisible(false);
		  RootLayoutPanel.get().add(mainLayout);   		 		 
	   
        }
       
		private void changeAccionPage(String name, NavigationPane navigationPane)
		{
			navigationPane.expandSection(0);
			navigationPane.selectRecord(name);
	        navigationPaneHeader.setContextAreaHeaderLabelContents(name);
		}
		
	    @SuppressWarnings("unused")
	    private class ApplicationMenuClickHandler implements ClickHandler
	     {
		     @Override
		     
			  public void onClick(MenuItemClickEvent event)
		      {
		       String applicationName = event.getItem().getTitle();
			   SC.say("You clicked: " + applicationName);
			  } 
         }
		  

         private class NavigationPaneClickHandler implements RecordClickHandler
         {
			@Override
			public void onRecordClick(RecordClickEvent event) {
			  
			  NavigationPaneRecord record = (NavigationPaneRecord) event.getRecord();	
			  History.newItem(record.getName());
              Cookies.setCookie(NameTokens.TOKEN,record.getName());
			  setContextAreaView(record);
			  
			}
		  }    
		  
		  private void setContextAreaView(NavigationPaneRecord record)
		  {
			
			String name = record.getName();
			navigationPaneHeader.setContextAreaHeaderLabelContents(name);	
		    ContextAreaFactory factory = record.getFactory();
			Canvas view = factory.create();
			southLayout.setMembers(westLayout, view);   
		  }
		  
		  private void setLoading(Button signInButton,boolean estado, String title, String style)
		  {
			  signInButton.setEnabled(estado);
	          signInButton.setStyleName(style);
	          signInButton.setText(title);
	      }

		
		
}
